//
//  HYLoginViewController.m
//  HaiYue
//
//  Created by skyline on 2018/1/9.
//  Copyright © 2018年 skyline. All rights reserved.
//

#import "HYLoginViewController.h"
#import "HYUserFuncButton.h"
@interface HYLoginViewController ()<HYTextFieldDelegate>
@property (nonatomic, strong) HYTextField *firstTextField;
@property (nonatomic, strong) HYTextField *secondTextField;
@property (nonatomic, strong) HYTextField *thirdTextField;
@property (nonatomic, strong) HYButton *mainBtn;
@property (nonatomic, strong) HYUserFuncButton *registerBtn;
@property (nonatomic, strong) HYUserFuncButton *resetBtn;
@property (nonatomic, strong) HYButton *tipsBtn;
@property (nonatomic, strong) HYUserModel *model;
@end

@implementation HYLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = LINE_COLOR;
    // Do any additional setup after loading the view.
}

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.type = HYLoginViewControllerTypeLogin;
    }
    return self;
}
- (HYTextField *)firstTextField
{
    if (!_firstTextField)
    {
        _firstTextField = [[HYTextField alloc]initWithPlaceholder:@""];
        _firstTextField.returnKeyType = UIReturnKeyNext;
        _firstTextField.hydelegate = self;
        [self.view addSubview:_firstTextField];
        [_firstTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).with.offset(GAP);
            make.left.equalTo(self.view).with.offset(GAP);
            make.right.equalTo(self.view).with.offset(-GAP);
            make.height.mas_equalTo(TextFieldHeight);
        }];
    }
    return _firstTextField;
}

- (HYTextField *)secondTextField
{
    if (!_secondTextField)
    {
        _secondTextField = [[HYTextField alloc]initWithPlaceholder:@""];
        _secondTextField.returnKeyType = UIReturnKeyDone;
        _secondTextField.hydelegate = self;
        [self.view addSubview:_secondTextField];
        [_secondTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.firstTextField.mas_bottom).with.offset(GAP);
            make.left.equalTo(self.view).with.offset(GAP);
            make.right.equalTo(self.view).with.offset(-GAP);
            make.height.mas_equalTo(TextFieldHeight);
        }];
    }
    return _secondTextField;
}

- (HYTextField *)thirdTextField
{
    if (!_thirdTextField)
    {
        _thirdTextField = [[HYTextField alloc]initWithPlaceholder:@""];
        _thirdTextField.verify = YES;
        [self.view addSubview:_thirdTextField];
        [_thirdTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.secondTextField.mas_bottom).with.offset(GAP);
            make.left.equalTo(self.view).with.offset(GAP);
            make.right.equalTo(self.view).with.offset(-GAP);
            make.height.mas_equalTo(TextFieldHeight);
        }];
    }
    return _thirdTextField;
}

- (HYButton *)mainBtn
{
    if (!_mainBtn)
    {
        _mainBtn = [[HYButton alloc]initWithTitle:@"" backColor:THEME_COLOR];
        [_mainBtn addTarget:self action:@selector(actionForMainButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_mainBtn];
        [_mainBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.secondTextField.mas_bottom).with.offset(GAP);
            make.left.equalTo(self.view).with.offset(GAP);
            make.right.equalTo(self.view).with.offset(-GAP);
            make.height.mas_equalTo(ButtonHeight);
        }];
    }
    return _mainBtn;
}

- (HYUserFuncButton *)registerBtn
{
    if (!_registerBtn)
    {
        _registerBtn = [[HYUserFuncButton alloc] initWithFrame:CGRectMake(0, 0, HYUserCenterButtonWidth, HYUserCenterButtonWidth)
                                                         title:@"注册" image:@"userlogin_register_nomal" selectImage:@"userlogin_register_selecter"];
        [_registerBtn addTarget:self action:@selector(actionForRegisterBtn) forControlEvents:UIControlEventTouchUpInside];
        _registerBtn.titleColor =  RGBA(235, 50, 35, 1);
        [self.view addSubview:_registerBtn];
        [_registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.mainBtn.mas_bottom).with.offset(GAP);
            make.left.equalTo(self.view).with.offset((SCREEN_WIDTH - HYUserCenterButtonWidth * 2) / 3.0);
            make.size.mas_equalTo(self.registerBtn.bounds.size);
        }];
    }
    return _registerBtn;
}

- (HYUserFuncButton *)resetBtn
{
    if (!_resetBtn)
    {
        _resetBtn = [[HYUserFuncButton alloc] initWithFrame:CGRectMake(0, 0, HYUserCenterButtonWidth, HYUserCenterButtonWidth)
                                                      title:@"忘记密码" image:@"userlogin_password_nomal" selectImage:@"userlogin_password_selecter"];
        [_resetBtn addTarget:self action:@selector(actionForResetBtn) forControlEvents:UIControlEventTouchUpInside];
        _resetBtn.titleColor = TEXT_GRAY_COLOR;
        [self.view addSubview:_resetBtn];
        [_resetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.mainBtn.mas_bottom).with.offset(GAP);
            make.right.equalTo(self.view).with.offset( -(SCREEN_WIDTH - HYUserCenterButtonWidth * 2) / 3.0);
            make.size.mas_equalTo(self.resetBtn.bounds.size);
        }];
    }
    return _resetBtn;
}

- (HYButton *)tipsBtn
{
    if (!_tipsBtn)
    {
        _tipsBtn = [[HYButton alloc] initWithTitle:@"用户名注册的" backColor:[UIColor clearColor]];
        _tipsBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_tipsBtn.titleLabel sizeToFit];
        [_tipsBtn setTitleColor:TEXT_GRAY_COLOR forState:UIControlStateNormal];
        [_tipsBtn addTarget:self action:@selector(actionForUserTipBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_tipsBtn];
        [_tipsBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.mainBtn);
            make.top.equalTo(self.mainBtn.mas_bottom).with.offset(GAP / 2.0);
            make.size.mas_equalTo(self.tipsBtn.titleLabel.bounds.size);
        }];
    }
    return _tipsBtn;
}

- (HYUserModel *)model
{
    if (!_model)
    {
        _model = [CCSave unarchiverObjFromFile:USER_MODEL];
    }
    return _model;
}

- (void)setDict:(NSDictionary *)dict
{
    if (_dict != dict)
    {
        _dict = dict;
        self.firstTextField.text = [[_dict allKeys] firstObject];
        self.secondTextField.text = [[_dict allValues] firstObject];
    }
}
- (void)setType:(HYLoginViewControllerType)type
{
    if (_type != type)
    {
        _type = type;
        
        self.registerBtn.hidden = self.resetBtn.hidden = YES;
        if (_type == HYLoginViewControllerTypeLogin)
        {
            self.navigationItem.title = @"用户登录";
            self.firstTextField.placeholder = @"请入用户名或者手机号码";
            self.firstTextField.type = HYTextFieldTypeAccount;
            self.secondTextField.placeholder = @"请输入密码";
            self.secondTextField.secureTextEntry = YES;
            self.secondTextField.type = HYTextFieldTypePassword;
            [self.mainBtn setTitle:@"登录" forState:UIControlStateNormal];
            self.registerBtn.hidden = self.resetBtn.hidden = NO;
        }
        else if (_type == HYLoginViewControllerTypePhoneRegister)
        {
            self.navigationItem.title = @"注册";
            self.firstTextField.placeholder = @"请输入11位手机号";
            self.firstTextField.type = HYTextFieldTypePhone;
            self.secondTextField.placeholder = @"请输入验证码";
            self.secondTextField.type = HYTextFieldTypeVerifyCode;
            self.secondTextField.verify = YES;
            self.secondTextField.secureTextEntry = NO;
            [self.mainBtn setTitle:@"下一步" forState:UIControlStateNormal];
            [self.tipsBtn setTitle:@"用户名注册" forState:UIControlStateNormal];
        }
        else if (_type == HYLoginViewControllerTypeUserNameRegister)
        {
            self.navigationItem.title = @"用户名注册";
            self.firstTextField.placeholder = @"请输入4-16位用户名,小写字母开头";
            self.firstTextField.type = HYTextFieldTypeAccount;
            self.secondTextField.placeholder = @"请输入6-16位密码";
            self.secondTextField.type = HYTextFieldTypePassword;
            [self.mainBtn setTitle:@"注册" forState:UIControlStateNormal];
        }
        else if (_type == HYLoginViewControllerTypeChangePassWord)
        {
            self.navigationItem.title = @"修改登录密码";
            self.firstTextField.placeholder = @"请输入原登录密码";
            self.secondTextField.placeholder = @"请输入6-16位新登录密码";
            [self.mainBtn setTitle:@"修改登录密码" forState:UIControlStateNormal];
            [self.tipsBtn setTitle:@"忘记登录密码" forState:UIControlStateNormal];
        }
        else if (_type == HYLoginViewControllerTypeResetPassWord)
        {
            self.navigationItem.title = @"重置密码";
            self.firstTextField.placeholder = @"请输入11位的手机号码";
            self.secondTextField.placeholder = @"请输入6-16位新密码";
            self.thirdTextField.placeholder = @"请输入验证码";
            [self.mainBtn setTitle:@"确定" forState:UIControlStateNormal];
            [self.mainBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.secondTextField.mas_bottom).with.offset(GAP * 2 + TextFieldHeight);
            }];
        }
        else if (_type == HYLoginViewControllerTypePayPassWord)
        {
            self.navigationItem.title = @"设置支付密码";
            self.firstTextField.placeholder = @"请输入6-16位支付密码";
            self.secondTextField.hidden = YES;
            [self.mainBtn setTitle:@"设置支付密码" forState:UIControlStateNormal];
            [self.mainBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.secondTextField.mas_bottom).with.offset(- TextFieldHeight);
            }];
        }
    }
}

- (void)actionForMainButton
{
    NSString *api = @"";
    switch (self.type) {
        case HYLoginViewControllerTypeLogin:
            api = API_USER_LOGIN;
            if (![self.firstTextField.text isNumberOrAlphabet])
            {
                [CCAlert showMessage:@"账号必须为字母或数字" hidden:nil];
                return;
            }
            else if (![self.secondTextField.text isNumberOrAlphabet])
            {
                [CCAlert showMessage:@"密码必须为字母或数字" hidden:nil];
                return;
            }
            break;
        case HYLoginViewControllerTypePhoneRegister:
            api = API_USER_REGISTER;
            if (![self.firstTextField.text isMobile])
            {
                [CCAlert showMessage:@"请输入正确的手机号码" hidden:nil];
                return;
            }
            else if (![self.secondTextField.text isNumber])
            {
                [CCAlert showMessage:@"请输入正确的验证码" hidden:nil];
                return;
            }
            break;
        case HYLoginViewControllerTypeUserNameRegister:
            api = API_USER_REGISTER;
            if (![self.firstTextField.text isLowercaseBetween:4 and:16])
            {
                [CCAlert showMessage:@"账号格式有误" hidden:nil];
                return;
            }
            else if (![self.secondTextField.text isLowercaseBetween:6 and:16])
            {
                [CCAlert showMessage:@"密码格式有误" hidden:nil];
                return;
            }
            break;
        case HYLoginViewControllerTypeChangePassWord:
            break;
        case HYLoginViewControllerTypeResetPassWord:
            if (![self.firstTextField.text isMobile])
            {
                [CCAlert showMessage:@"请输入正确的手机号码" hidden:nil];
                return;
            }
            else if (![self.secondTextField.text isLowercaseBetween:6 and:16])
            {
                [CCAlert showMessage:@"密码格式有误" hidden:nil];
                return;
            }
            else if (![self.thirdTextField.text isNumber])
            {
                [CCAlert showMessage:@"请输入正确的验证码" hidden:nil];
                return;
            }
            break;
        case HYLoginViewControllerTypePayPassWord:
            break;
        default:
            break;
    }
    [self startHUD];
    //13061861860    123456
    
    [CCHttp post:api para:@{@"account":self.firstTextField.text,@"password":self.secondTextField.text} success:^(id  _Nonnull response) {
        [self endHUD];
        self.model = [HYUserModel mj_objectWithKeyValues:response];
        self.model.passmm = self.secondTextField.text;
        [CCAlert showMessage:self.model.msg hidden:^{
            if (self.model.retcode == 100)
            {
                [CCSave archiver:self.model toFile:USER_MODEL];
                
                for (HYViewController *vc in self.navigationController.viewControllers)
                {
                    //如果是注册 || 找回密码, 返回到登录界面
                    if (self.type != HYLoginViewControllerTypeLogin && self.type != HYLoginViewControllerTypePayPassWord)
                    {
                        if ([vc isKindOfClass:[HYLoginViewController class]])
                        {
                            HYLoginViewController *new_vc = (HYLoginViewController *)vc;
                            new_vc.type = HYLoginViewControllerTypeLogin;
                            new_vc.dict = @{self.firstTextField.text:self.secondTextField.text};
                            [self.navigationController popToViewController:new_vc animated:YES];
                            break;
                        }
                    }
                    
                    //如果是登录，返回到个人中心
                    else
                    {
                        [self.navigationController popViewControllerAnimated:YES];
                        break;
                        //                        if ([vc isKindOfClass:NSClassFromString(@"HYMyAssetsViewController")])
                        //                        {
                        //                            [self.navigationController popViewControllerAnimated:YES];
                        //                            [self.navigationController popToViewController:vc animated:YES];
                        //                        }
                    }
                }
            }
        }];
    } fail:^(NSError * _Nonnull error) {
        
    }];
    
    //    [HYHttps post:api para:@{@"account":self.firstTextField.text,@"password":self.secondTextField.text} complete:^(id response) {
    //        [self endHUD];
    //        self.model = [HYUserModel mj_objectWithKeyValues:response];
    //        self.model.passmm = self.secondTextField.text;
    //        [CCAlert showMessage:self.model.msg hidden:^{
    //            if (self.model.retcode == 100)
    //            {
    //                [CCSave archiver:self.model toFile:USER_MODEL];
    //
    //                for (HYViewController *vc in self.navigationController.viewControllers)
    //                {
    //                    //如果是注册 || 找回密码, 返回到登录界面
    //                    if (self.type != HYLoginViewControllerTypeLogin && self.type != HYLoginViewControllerTypePayPassWord)
    //                    {
    //                        if ([vc isKindOfClass:[HYLoginViewController class]])
    //                        {
    //                            HYLoginViewController *new_vc = (HYLoginViewController *)vc;
    //                            new_vc.type = HYLoginViewControllerTypeLogin;
    //                            new_vc.dict = @{self.firstTextField.text:self.secondTextField.text};
    //                            [self.navigationController popToViewController:new_vc animated:YES];
    //                            break;
    //                        }
    //                    }
    //
    //                    //如果是登录，返回到个人中心
    //                    else
    //                    {
    //                        [self.navigationController popViewControllerAnimated:YES];
    //                        break;
    //                        //                        if ([vc isKindOfClass:NSClassFromString(@"HYMyAssetsViewController")])
    //                        //                        {
    //                        //                            [self.navigationController popViewControllerAnimated:YES];
    //                        //                            [self.navigationController popToViewController:vc animated:YES];
    //                        //                        }
    //                    }
    //                }
    //            }
    //        }];
    //    } fail:^(NSDictionary *dict) {
    //
    //    }];
}

- (void)actionForRegisterBtn
{
    if (IS_APPStore) [self pushVC:HYLoginViewControllerTypePhoneRegister];
    else [self pushVC:HYLoginViewControllerTypeUserNameRegister];
}

- (void)actionForResetBtn
{
    if (IS_APPStore)
        [self pushVC:HYLoginViewControllerTypeResetPassWord];
}

- (void)actionForUserTipBtn
{
    HYLoginViewControllerType type = (self.type == HYLoginViewControllerTypePhoneRegister)?HYLoginViewControllerTypeUserNameRegister:HYLoginViewControllerTypeResetPassWord;
    [self pushVC:type];
}

- (void)pushVC:(HYLoginViewControllerType)type
{
    HYLoginViewController *VC = [[HYLoginViewController alloc]init];
    VC.type = type;
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark HYTextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([textField isEqual:self.firstTextField] && textField.returnKeyType == UIReturnKeyNext)
    {
        [self.secondTextField becomeFirstResponder];
    }
    else if ([textField isEqual:self.secondTextField] && textField.returnKeyType == UIReturnKeyNext)
    {
        [self.thirdTextField becomeFirstResponder];
    }
    return YES;
}
- (BOOL)shouldVerifycationCode
{
    if (![self.firstTextField.text isMobile])
    {
        [CCAlert showMessage:@"手机号码有误" hidden:nil];
        return NO;
    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.style = HYViewNaviBarStyleOnlyLeftBtn;
    if ([HYUserManager manager].user && [[HYUserManager manager].user.account length] > 0)
    {
        self.firstTextField.text = [HYUserManager manager].user.account;
        self.secondTextField.text = [HYUserManager manager].user.passmm;
    }
    else
        [self.firstTextField becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (_type == HYLoginViewControllerTypePhoneRegister)
    {
        [_secondTextField stopTimer];
    }
    else if (_type == HYLoginViewControllerTypeResetPassWord)
    {
        [_thirdTextField stopTimer];
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
